﻿using System;
using System.Activities;

namespace Foulds.Calculator.StateMachine.Input
{
    /// <summary>
    /// This code activity allows the state machine to process a calculator key press from the user.
    /// </summary>
    public sealed class ReadCalculatorKey : NativeActivity<CalculatorKey>
    {
        #region Member Variables
        [RequiredArgument]
        public InArgument<string> BookmarkName { get; set; }
        #endregion

        #region Properties

        #region Can Include Idle
        ///<summary>
        /// NativeActivity derived activities that do asynchronous operations by calling 
        /// one of the CreateBookmark overloads defined on System.Activities.NativeActivityContext 
        /// must override the CanInduceIdle property and return true.
        /// </summary>
        protected override bool CanInduceIdle
        {
            get { return true; }
        }
        #endregion

        #endregion

        #region Execute
        /// <summary>
        /// Execute the logic for the code activity.
        /// </summary>
        protected override void Execute(NativeActivityContext context)
        {
            // ensure that a bookmark name was provided
            string bookmarkName = this.BookmarkName.Get(context);
            if (bookmarkName == string.Empty)
                throw new ArgumentException("BookmarkName cannot be an Empty string.", "BookmarkName");

            // create the bookmark
            context.CreateBookmark(bookmarkName, OnReadComplete);
        }
        #endregion

        #region On Read Complete
        /// <summary>
        /// This is the callback function to execute once the read completes.
        /// </summary>
        private void OnReadComplete(NativeActivityContext context, Bookmark bookmark, object state)
        {
            this.Result.Set(context, (CalculatorKey)state);
        }
        #endregion
    }
}
